﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Romeo.Data
{
    public class LockedCellEvaluator : Evaluator
    {
        private bool[] _Locked = new bool[Board.CellCount];
        private int _Score;
        private sbyte[] _Cells;
        private int _LockScore = 100000;

        private bool Check (int aCell, int aDir, sbyte aPlayer)
        {
            return (_Cells[aCell + aDir] == Board.Invalid || (_Cells[aCell + aDir] == aPlayer && _Locked[aCell + aDir]))
                || (_Cells[aCell - aDir] == Board.Invalid || (_Cells[aCell - aDir] == aPlayer && _Locked[aCell - aDir]));
        }

        private void Check (int aCell)
        {
            sbyte p = _Cells[aCell];
            if (p == Board.Empty || p == Board.Invalid || _Locked[aCell])
            {
                return;
            }

            if (Check (aCell, 1, p) && Check (aCell, 9, p) && Check (aCell, 10, p) && Check (aCell, 11, p))
            {
                _Score += _LockScore * p;
                _Locked[aCell] = true;
                Check (aCell + 1);
                Check (aCell + 9);
                Check (aCell + 10);
                Check (aCell + 11);
                Check (aCell - 1);
                Check (aCell - 9);
                Check (aCell - 10);
                Check (aCell - 11);
            }
        }

        public override int Evaluate (Board aBoard, int aMinScore)
        {
            Array.Clear (_Locked, Board.StartCell, Board.UsableCount);
            _Score = 0;
            _Cells = aBoard._Cells;
            Check (11);
            Check (18);
            Check (81);
            Check (88);
            return _Score;
        }
    }
}
